<?php
include_once  'BaseService.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/ad/sys/com/model/db/AdDAO.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/ad/sys/com/model/db/UserDAO.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/ad/sys/com/model/db/AdCategorDAO.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/ad/sys/com/model/util/Util.php'; 

class AdService extends BaseService {
	public function __construct(){
		parent::__construct();
	 	parent::setTarget($this);	
	 	$this->log = Plog::factory(__FILE__);	
	}
	
	public function updateAdIsNew() {
		$adDAO = new AdDAO();
		$adDAO->updateAdIsNew();
	}
	
	
	public function managerAd() {	
		$proxyName = $this->getRequest("proxyName");
		$name =  $this->getRequest("name");
		$startDate =  $this->getRequest("startDate");
		$endDate =  $this->getRequest("endDate");
		$status  = $this->getRequest("status");
		
		$start = $this->getRequest("start");
		$limit =  $this->getRequest("limit");
		
		$adDAO = new AdDAO();
		$result =  $adDAO-> managerAd($proxyName, $name, $startDate, $endDate, $status, $start , $limit);
		
		echo "{count:".$result["count"].",row:".Util::toJson($result["items"])."}";
	}
	
	public function updateAdPay() {
		$adId = $_GET["adId"];
		$isPay = $_GET["isPay"];
		
		$adDAO = new AdDAO();
		$result =  $adDAO-> updateAdPay($adId, $isPay);
		echo "{result : $result}";
	}
	
	public function  updateAd() {
		$status = $_POST["status"];
		$description  = $_POST["description"];
		$adId = $_POST["adId"];
		$adName = $_POST["adName"];	
	
		$adDAO = new AdDAO();
		$result =  $adDAO-> updateAd($adId, $status, $description,$adName);
		
		
	    $sendDesc = "";
	    
	    if ($description != "") {
	    	$sendDesc = "備註:".$description;
	    }
		
		//審核成功
		
		if ($result == 1) {
			$ad =  $adDAO->getAdById($adId);
	 
			$userDAO = new UserDAO();
			$user = $userDAO->getUserByAccount($ad->Account);
			
			if ($status =="1" && $user ->NotifyAdApproved ==1) { //廣告已經核准
				Util::email($user->Account, "Amazing Mobile ADs通知：您的廣告已經批准",
					"
						親愛的 $user->Name 您好， <BR>
					  <BR>
				 	  感謝您購買Amazing Mobile Ads廣告， <BR>
					   您申請的 $ad->AdName 活動廣告，已審核通過，將於 $ad->AdStartDate 開始刊登。 <BR>
					  請注意，我們只會根據您的廣告所收到的展示次數或點擊量收取廣告費用。廣告刊登總金額將不會超過您所設定的每日行銷預算。 <BR>
					  如果您對於廣告上有任何問題，請來信至: service@ai-ad.net.tw <BR><BR>
					   
					   謝謝您， <BR>
					 Amazing Mobile Ads敬上<BR><BR> 
					 
					 <font color=red> $sendDesc </font> 
					"
				);
			} else if ($status =="5" && $user ->NotifyAdApprovedNot) { //廣告審核未通過
				Util::email($user->Account, 
					"Amazing Mobile ADs通知：您的廣告刊登審核未通過",
					"
						親愛的 $user->Name 您好， <BR> <BR>
						 
						感謝您購買Amazing Mobile Ads廣告， <BR>
						您的 $ad->AdName 活動廣告，未能通審核，請再重新申請。 <BR>
						請注意，我們只會根據您的廣告所收到的展示次數或點擊量收取廣告費用。廣告刊登總金額將不會超過您所設定的每日行銷預算。 <BR>
						如果您對於廣告上有任何問題，請來信至: service@ai-ad.net.tw <BR><BR>
						 
						 
						謝謝您， <BR>
						Amazing Mobile Ads敬上<BR><BR> 
					 
					 	<font color=red> $sendDesc </font> 
					"
				);
				
			} else if ($status =="6" && $user->NotifyAdModify ==1) { //廣告需要修改
				Util::email($user->Account, 
					"Amazing Mobile ADs通知：您的廣告刊登需要修改",
					"
						親愛的 $user->Name 您好，  <BR> <BR>
 
						感謝您購買Amazing Mobile Ads廣告，<BR>
						您的 $ad->AdName 活動廣告，未能通審核，請再進行修改。<BR>
						請注意，我們只會根據您的廣告所收到的展示次數或點擊量收取廣告費用。廣告刊登總金額將不會超過您所設定的每日行銷預算。<BR>
						如果您對於廣告上有任何問題，請來信至: service@ai-ad.net.tw<BR><BR>

						 
						
						謝謝您，<BR>
						Amazing Mobile Ads敬上 <BR><BR> 
					 
					 	<font color=red> $sendDesc </font> 
					"
				);
				
			}
		}  
		echo "{result : $result}";
	}
	
	public function getAdReport() {
		$account = $_GET["account"];
		$start = $_REQUEST["start"];
		$limit = $_REQUEST["limit"];
 		//echo "test:$start , $limit"; 
		$ad = new AdDAO();
		$result = $ad->getAdReportByAcount($account,$start, $limit);
		 
		echo "{count:".$result["count"].",row:".Util::toJson($result["items"])."}";
	}
	
	public function getAdById() {
		$adId = $_GET["adId"];
		$adDAO = new AdDAO();
		$result = $adDAO->getAdById($adId);
		echo Util::toJson($result);
	}
	
	/**
	 * 查詢廣告依據使用者帳號
	 */
	public function getAdByAccount() {
		$account = $_GET["account"];
		$adDAO = new AdDAO();
		$result = $adDAO->getAdByAccount($account);
		echo Util::toJson($result);
	}
	 
	 /**
	 * 廣告管理查詢
	 */
	public  function menagerAd() {
		//session_start();
		//$user = Util::jsonToObject($_SESSION["user"]);
		$adDAO = new AdDAO();
		$result = $adDAO->menagerAd($_GET["account"]);
		 
		echo Util::toJson($result);
		
	}
	 
	/**
	 * 取得該使用者的廣告帳務
	 * Enter description here ...
	 */
	public function getAccountSettle () {
		$account = $_GET["account"];
		$start = $_POST["start"];
		$limit = $_POST["limit"];
 		
		$ad = new AdDAO();
		$result = $ad->getAccountSettle($start, $limit, $account);
		 
		echo "{count:".$result["count"].",row:".Util::toJson($result["item"])."}";
	}
	
	 
	/**
	 * 查詢廣告依據日期跟狀態
	 * Enter description here ...
	 */
	public function queryAdByCreatetimeAndStatus() {
		 
		$whereData =   isset($_POST["whereDate"]) ?  $_POST["whereDate"] : "";
		$whereStatus = isset($_POST["whereStatus"]) ?  $_POST["whereStatus"] : "";
		 
		$account = $_GET["account"];
		$start =  $_POST["start"];
		$limit = $_POST["limit"];
		//$desc = $_REQUEST["desc"];
	 
		$adDAO = new AdDAO();
		
		$result = $adDAO->queryAdByCreatetimeAndStatus($start, $limit,$account, $whereData, $whereStatus);

		echo "{count:".$result["count"].",row:".Util::toJson($result["item"])."}";
	}
	/**
	 * 建立新增廣告Session
	 * Enter description here ...
	 */
	private function createAdSeeion() {
		session_start();
		if (isset($_SESSION["ad"])) {
			return $_SESSION["ad"];
		} else {
			$_SESSION["ad"] = array("action"=>"new", "account" => null);
			return $_SESSION["ad"];
		}
	}
	
	public function clearToAd() {
		session_start();
		if (isset($_SESSION["ad"])) {
			unset($_SESSION["ad"]);
		}
		Util::forward("/ad/html/frontoffice/tigerStep1.php"); 	
	}
	
	public function toAdd() {
		$account = $_GET["account"];
		
		$ad =  $this->createAdSeeion();
		$ad["account"] = $account;
		$_SESSION["ad"] = $ad;
		Util::forward("/ad/html/frontoffice/tigerStep1.php"); 	 
	}
	
	public function tigetStep1Action(){
		$adId = $_GET["adId"];
		
		$adDAO = new AdDAO();
		
		$adObj =  $adDAO->getAdToArray($adId);
		
		$adCategorDAO  = new  AdCategorDAO();
		
		$adCategor = $adCategorDAO->getAdCategor($adId);
		
		$ad = array("action"=>"tigetEdit");
		$ad["adId"] =$adId;
		$ad["account"] = $adObj["Account"];
		$ad["title"] = $adObj["Title"];
		$ad["image1"] = $adObj["Image1"];
		$ad["image2"] = $adObj["Image2"];
		$ad["url"] = $adObj["Url"];
		$ad["clickAction"] = $adObj["ClickAction"];
		
		$ad["ageStart"] = $adObj["AgeStart"];
		$ad["ageEnd"] = $adObj["AgeEnd"];
		$ad["area"] = $adObj["Area"];
		$ad["areaName"] = $adObj["AreaName"];
		$ad["sex"] = $adObj["Sex"];
		$ad["category"] =  $adCategor;
		
		$ad["adName"] =$adObj["AdName"];
		$ad["budget"] = $adObj["Budget"];
		$ad["adBudgetType"] = $adObj["AdBudgetType"];
		$ad["adStartDate"] = $adObj["AdStartDate"];
		$ad["adEndDate"] = $adObj["AdEndDate"];
		$ad["adBillingType"] = $adObj["AdBillingType"];
		 
		session_start();
		$_SESSION["ad"] = $ad;
		
		Util::forward("/ad/html/frontoffice/tigerStep1.php"); 	 
	}
	
	public function managerStep1Action(){
		$adId = $_GET["adId"];
		
		$adDAO = new AdDAO();
		
		$adObj =  $adDAO->getAdToArray($adId);
		
		$adCategorDAO  = new  AdCategorDAO();
		
		$adCategor = $adCategorDAO->getAdCategor($adId);
		
		$ad = array("action"=>"managerEdit");
		$ad["adId"] =$adId;
		$ad["account"] = $adObj["Account"];
		$ad["title"] = $adObj["Title"];
		$ad["image1"] = $adObj["Image1"];
		$ad["image2"] = $adObj["Image2"];
		$ad["url"] = $adObj["Url"];
		$ad["clickAction"] = $adObj["ClickAction"];
		
		$ad["ageStart"] = $adObj["AgeStart"];
		$ad["ageEnd"] = $adObj["AgeEnd"];
		$ad["area"] = $adObj["Area"];
		$ad["areaName"] = $adObj["AreaName"];
		$ad["sex"] = $adObj["Sex"];
		$ad["category"] =  $adCategor;
		
		$ad["adName"] =$adObj["AdName"];
		$ad["budget"] = $adObj["Budget"];
		$ad["adBudgetType"] = $adObj["AdBudgetType"];
		$ad["adStartDate"] = $adObj["AdStartDate"];
		$ad["adEndDate"] = $adObj["AdEndDate"];
		$ad["adBillingType"] = $adObj["AdBillingType"];
		 
		session_start();
		$_SESSION["ad"] = $ad;
		
		Util::forward("/ad/html/frontoffice/tigerStep1.php"); 	 
	}
	
	 
	public function step1Action(){
		$ad = $this::createAdSeeion();
		$ad["title"] = $_POST["title"];
		$ad["image1"] = $_POST["image1"];
		$ad["image2"] = $_POST["image2"];
		$ad["url"] = $_POST["url"];
		$ad["clickAction"] = $_POST["clickAction"];
		$_SESSION["ad"] = $ad;
		Util::forward("/ad/html/frontoffice/tigerStep2.php");	 
	}
	
	/**
	 * 前往 新增廣告 step2
	 * Enter description here ...
	 */
	public function step2Action(){
		$ad = $this::createAdSeeion();
		$ad["ageStart"] = $_POST["ageStart"];
		$ad["ageEnd"] = $_POST["ageEnd"];
		$ad["area"] = $_POST["area"];
		$ad["areaName"] = $_POST["areaName"];
		$ad["sex"] = $_POST["sex"];
		$ad["category"] = $_POST["category"];
		$_SESSION["ad"] = $ad;
		Util::forward("/ad/html/frontoffice/tigerStep3.php");
	}
	
	/**
	 * 前往 新增廣告 step3
	 * Enter description here ...
	 */
	public function step3Action(){
		$ad = $this::createAdSeeion();
		$ad["adName"] =$_POST["adName"];
		$ad["budget"] = $_POST["budget"];
		$ad["adBudgetType"] = $_POST["adBudgetType"];
		$ad["adStartDate"] = $_POST["adStartDate"];
		$ad["adEndDate"] = $_POST["adEndDate"];
		$ad["adBillingType"] = $_POST["adBillingType"];
		$_SESSION["ad"] = $ad;
		Util::forward("/ad/html/frontoffice/tigerStep4.php");
	}
 
	
	private function addAd($ad) {
		$user = Util::jsonToObject($_SESSION["user"]);
		$isManager = true; 
		if (is_null($ad->account) || $ad->account =="") {
			$ad->account= $user->Account;
			$isManager = false;
		}
		
		$adDAO = new AdDAO();
	    
		$result = $adDAO->newAd($ad);
		if ($result["count"] ==1) {
			
			$userDAO = new UserDAO();
			$sends =  $userDAO->getMenagerUserAccount();
			$nowdate = Util::getNowDate();
			Util::email(
				$sends, 
				"Amazing Mobile ADs通知：會員 $user->Name 新增廣告",
			    "會員 $user->Name 於$nowdate <BR>
			             刊登一則 $ad->adName 活動廣告內容，<BR>
				  請盡速至 <a href='http://mmedia.ai-ad.net.tw//ad/html/backoffice/backofficeLogin.php'>http://mmedia.ai-ad.net.tw//ad/html/backoffice/backofficeLogin.php</a> 進行審核。<BR><BR>
				 
				  謝謝您，<BR>
				 Amazing Mobile Ads工作團隊<BR>
			    "
			); 
			
			//clear as session
			unset($_SESSION["ad"]);
			Util::alert('新增廣告成功,請等待管理者審核!');
			if ($isManager) {
				Util::forward("/ad/html/backoffice/backofficeMAdList.php?customAccount=".$ad->account);
			} else {
				Util::forward("/ad/html/frontoffice/tigerManageAd.php");
			}
			
			
		} else {
			Util::alert('新增廣告失敗,請稍後新增或請洽管理員!');
			Util::forward("/ad/html/frontoffice/tigerStep4.php");
		} 
		
	}
	
	private function modifyAd($ad) {
		$adDAO = new AdDAO();
	    
		$result = $adDAO->modifyAd($ad);
		if ($result==1) {
			//clear as session
			unset($_SESSION["ad"]);
			Util::alert('修改廣告成功!');
			Util::forward("/ad/html/backoffice/backofficeMAdList.php?customAccount=".$ad->account);
		} else {
			Util::alert('修改廣告失敗!');
			Util::forward("/ad/html/frontoffice/tigerStep4.php");
		}
	}
	
	
	private function tigetEditAd($ad) {
		$adDAO = new AdDAO();
	    
		$result = $adDAO->modifyAd($ad);
		if ($result==1) {
			//clear as session
			unset($_SESSION["ad"]);
			Util::alert('修改廣告成功!');
			Util::forward("/ad/html/frontoffice/tigerManageAd.php");
		} else {
			Util::alert('修改廣告失敗!');
			Util::forward("/ad/html/frontoffice/tigerStep4.php");
		}
	}
	
	
	/**
	 * 完成 新增廣告
	 * Enter description here ...
	 */
	public function complete() {
		$ad = (Object)$this::createAdSeeion();
		if ($ad->action =="new") {
			$this->addAd($ad);
		} else if  ($ad->action =="tigetEdit") {
			$this->tigetEditAd($ad);
		} else if ($ad->action == "managerEdit"){
			$this->modifyAd($ad);
		}
	}
	
	
	public function exportExcelMaager() {
		$account =  $_GET["account"];
		$id = $_GET["id"];
		$adStartDate = $_GET["adStartDate"];
		$adEndDate =  $_GET["adEndDate"];
		$adBudgetType =  $_GET["adBudgetType"];
		
		$adDAO = new AdDAO();
		$result = $adDAO->getManagerReport($account,$id , $adStartDate, $adEndDate, $adBudgetType);
		
		$filename = "Ad Report";
		$en = array("A","B","C","D","E","F","G","H");
		$titles =array(
			"$en[0]1" => "廣告名稱",
		    "$en[1]1" => "日期區間(起)",
		    "$en[2]1" => "日期區間(迄)",
		    "$en[3]1" => "廣告 ID",
		    "$en[4]1" => "曝光次數",
		    "$en[5]1" => "點擊次數",
		    "$en[6]1" => "點閱率",
		    "$en[7]1" => "成本"
		);
		
		$contents = array();
		$j=2;
		foreach ($result as $obj) {
			$contents[] = array(
				"$en[0]$j" => $obj->AdName,
			    "$en[1]$j" => $obj->AdStartDate,
			    "$en[2]$j" => $obj ->AdEndDate,
			    "$en[3]$j" => $obj->Id,
			    "$en[4]$j" => $obj->ActualImpressions,
			     "$en[5]$j" => $obj->ActuaClick,
			    "$en[6]$j" => $obj->ClickRate."%",
			    "$en[7]$j" => $obj->point//待開發 成本
			);
			$j++; 
		}
	    
		//匯出Excel
		Util::excel($filename, $titles, $contents); 
	}
	
	public function queryAd()
	{
		$md5key = $_REQUEST["md5key"];
		$imei = $_REQUEST["IMEI"];
		$ad = new AdDAO();
		@$result = $ad->queryAd($md5key,$imei);
		//echo print_r($result);
		echo Util::toJson($result);
		//echo "<a id='adLink' href='http://mmedia.ai-ad.net.tw/Banner/WebClick.php?BannerID=AS001'><img src='".$result["item"][0]->Image1."' width='480' height='80'  /></a>";
		//echo "<a href=''>"($result["item"][0]->Image1);
		
	}
	public function clickAd()
	{
		$md5key = $_REQUEST["md5key"];
		$imei = $_REQUEST["IMEI"];
		$adId = $_REQUEST["adId"];
		//echo "appId=$appId<br/>imei=$imei<br/>adId=$adId<br/>";
		$ad = new AdDAO();
		$result = $ad->clickAd($md5key,$imei,$adId);
		//echo print_r($result);
		echo Util::toJson($result);
		//echo "<a id='adLink' href='http://mmedia.ai-ad.net.tw/Banner/WebClick.php?BannerID=AS001'><img src='".$result["item"][0]->Image1."' width='480' height='80'  /></a>";
		//echo "<a href=''>"($result["item"][0]->Image1);
		
	}
	
	
	
}

$service =  new AdService();
$service->__call($_GET["action"], null);
//$service->exportExcelMaager();
?>